package com.zpf.web.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * 抽取servlet
 *
 * projectName:2022ZPF
 * author:
 * time:2022/4/19 0:22
 * description:
 */
public class BaseServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     request.setCharacterEncoding("utf-8");

        //1.获取参数中的method
        String param = request.getParameter("method");
        //2.获取要执行的方法对象（反射）
        try {
            //通过反射获取要执行的方法
            Method method= this.getClass().getMethod(param,HttpServletRequest.class,HttpServletResponse.class);
            //执行方法(result是犯法的返回值)
          Object result=  method.invoke(this,request,response);
            //如果是重定向，约定前缀是redirect
            if(result == null) {
                //认为前端是ajax
            }
            //否则需要请求转发与重定向
            else {
                String res = result.toString();
                //如果是重定向： 约定前缀为 redirect
                if(res.startsWith("redirect:")){
                    //对res进行切割
                    String[] arr = res.split(":");
                    if(arr!= null && arr.length > 1){
                        response.sendRedirect(arr[1]);
                    }
                }
                //如果是请求转发， 约定前缀为 forward
                else {
                    //对res进行切割
                    String[] arr = res.split(":");
                    if(arr!= null && arr.length > 1){
                        request.getRequestDispatcher(arr[1]).forward(request, response);
                    }
                }
            }
            //如果是请求转发，约定前缀是forward

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("调用方法失败"+e.getMessage());
        }

    }
}